//
//  WbComposeView.swift
//  Weibo
//
//  Created by HH on 16/12/9.
//  Copyright © 2016年 Weibo. All rights reserved.
//

import UIKit
import pop

class WbComposeView: WbBaseView {
    
    //要添加的控制器
    var target:UIViewController?
    //截屏视图
    var screenShotView = UIImageView()
    //存储compose按钮数据
    var composeArray:[WbComposeMenu] = [WbComposeMenu]()
    //数组存储Compose按钮
    var composeBtnArr:[WbComposeButton] = [WbComposeButton]()
    
    

    override func setupUI() {
        
        
        
        //加载数据
        loadComposePlist()
        //一定要设置大小
        frame = (UIApplication.shared.keyWindow?.bounds)!
        
        addSubview(screenShotView)
        addComposeButton()
        
        screenShotView.frame = frame
        
        //毛玻璃效果
        screenShotView.image = screenShot().applyLightEffect()
        
        startAnimation(isUp: true)
    }
    
    
    //展示自己
    func show(target:UIViewController){
        
        self.target = target
        
        target.view.addSubview(self)
        
        
    }
    
    //截取当前屏幕
    private func screenShot()->UIImage{
        
        let window = UIApplication.shared.keyWindow
        
        UIGraphicsBeginImageContext((window?.size)!)
        
        window?.drawHierarchy(in: (window?.frame)!, afterScreenUpdates: false)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        //结束
        UIGraphicsEndImageContext()
        
        return image!
        
    }
    
    
    //添加6个compose按钮,并设置大小
    private func addComposeButton(){
        
        let composeWidth:CGFloat = 80
        let composeHeight:CGFloat = 100
        
        let composeMarign = (ScreenWidth - 3 * composeWidth) / 4
        
        
        for (i,model) in composeArray.enumerated(){
            
            let row = i / 3
            
            let col = i % 3
            
            let composeBtn = WbComposeButton(title: model.title, image: UIImage(named:model.icon!), backgroundImage: nil, font: 15, textColor: UIColor.black)
            //记录一个tag值,要利用tag值在ComposeBtn数组中取出对应的btn
            composeBtn.tag = i
            
            let composeX = composeMarign + (composeWidth + composeMarign) * CGFloat(col)
            
            let composeY = ScreenHeight + CGFloat(row) * (composeHeight + composeMarign)
            
            composeBtn.frame = CGRect(x: composeX, y: composeY, width: composeWidth, height: composeHeight)
            
            composeBtn.addTarget(self, action: #selector(btnAction(sender:)), for: .touchUpInside)
            
            addSubview(composeBtn)
            
            composeBtnArr.append(composeBtn)
        }
    
    }
    
    //按钮点击事件及动画
    @objc private func btnAction(sender:UIButton){
        
        UIView.animate(withDuration: 0.3, animations: {
            
            for btn in self.composeBtnArr{
                
                //是这个button则进行放大动画
                if sender == btn{
                    
                    sender.transform = CGAffineTransform(scaleX: 1.6, y: 1.6)
                }else{
                    //不是这个button则进行缩小动画
                    btn.transform = CGAffineTransform(scaleX: 0.3, y: 0.3)
                }
                
                btn.alpha = 0
                
            }
            
            
        }) { (_) in
            
            
            let model = self.composeArray[sender.tag]
            
            let classType = NSClassFromString(model.className!) as! UIViewController.Type
            
            let composeController = classType.init()
            
            let navController = WbNavigationController(rootViewController: composeController)
            
            self.target?.present(navController, animated: true, completion: nil)
            
//            self.removeFromSuperview()
            
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: {
                
                print("composeView从父控件中移除")
                self.removeFromSuperview()
            })
            
            //在放大缩小动画完成后将所有按钮恢复原状
//            UIView.animate(withDuration: 0.25, animations: { 
//                
//                for btn in self.composeBtnArr{
//                    
//                    btn.transform = CGAffineTransform.identity
//                    
//                }
//                
//            }, completion: { (_) in
//                
//                //跳转到对应的控制器
//                
//                
//            })
            
        }
        
    }
    
    //是否开启pop动画
    private func startAnimation(isUp:Bool){
        
        
        if isUp == false {
            composeBtnArr = composeBtnArr.reversed()
        }
        
        for (i,btn) in composeBtnArr.enumerated() {
            
            let pop = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            
            if isUp {
                
                pop?.toValue = CGPoint(x: btn.centerX, y: btn.centerY - 350)
                
            }else{
                
                pop?.toValue = CGPoint(x: btn.centerX, y: btn.centerY + 350)
            }
            
            
            pop?.springSpeed = 10
            
            pop?.springBounciness = 10
            
            pop?.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            
            
            btn.pop_add(pop, forKey: "pop")
            
        }
        
    }
    
    
    //从plist中读取compose按钮信息
    private func loadComposePlist(){
    
        let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)
        
        let dictArray = NSArray(contentsOfFile: path!) as! [[String:Any]]
        
        composeArray = NSArray.yy_modelArray(with: WbComposeMenu.self, json: dictArray) as! [WbComposeMenu]
        
    }
    
    //点击屏幕使自身移除父控件
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        self.startAnimation(isUp: false)
        
//        UIView.animate(withDuration: 1, animations: {
//              self.startAnimation(isUp: false)
//        }) { (_) in
//             self.removeFromSuperview()
//        }
        
        //需要延迟一些时间,使动画结束后,在从父控件中移除自身
        //头尾式动画在此处无效
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3, execute: {
            self.removeFromSuperview()
        })
        
    }
    
    

}
